from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.admin.views.decorators import staff_member_required

from django.core.urlresolvers import reverse

from pr_j.models import Project, Category
from pr_j.admin.forms import ProjectForm, CategoryForm


from s_te.utils import delete_slug

@staff_member_required
def main(request, template_name="pr_j/admin/main.html"):
    """
    Project admin, listing all projects
    """
    projects = Project.objects.all()
    return render_to_response(template_name, {'projects':projects, 'nav_page': 'pr_j_admin_main'},
                              context_instance=RequestContext(request))
    
@staff_member_required
def create(request, template_name="pr_j/admin/create.html"):
    """
    Create a new project
    """
    if request.POST:
        form = ProjectForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Project created.")
            return HttpResponseRedirect(reverse('pr_j_admin_main'))
    else:
        form = ProjectForm()
    return render_to_response(template_name, {'form':form},
                              context_instance=RequestContext(request))
    
@staff_member_required
def edit(request, slug, template_name="pr_j/admin/edit.html"):
    """
    Edit an existing project
    """
    project = get_object_or_404(Project, slug=slug)
    if request.POST:
        form = ProjectForm(request.POST, request.FILES, instance=project)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Project saved.")
            return HttpResponseRedirect(reverse('pr_j_admin_main'))
    else:
        form = ProjectForm(instance=project)
    return render_to_response(template_name, {'project':project, 'form':form},
                              context_instance=RequestContext(request))

@staff_member_required
def delete(request):
    """
    Delete an existing project
    """
    delete_slug(Project, request)
    request.user.message_set.create(message="Project deleted.")
    return HttpResponseRedirect(reverse('pr_j_admin_main'))
